package com.android.serialport.analysis;

import com.rfid.analysis.Handler;
import com.rfid.analysis.Message;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * @author Administrator
 * @date 2021/2/1
 */
public class HandleHeader extends Handler {

    @Override
    public void handleRequest(Message request) {
        request.setCurrentNodeHandler(this);
        ByteBuffer byteBuffer = request.getBuffer();
        request.setHasComplete(false);
        byte[] head = getHeader();
        while (byteBuffer.position() + head.length <= byteBuffer.limit()) {
            byteBuffer.mark();
            byte[] bufferHead = new byte[head.length];
            byteBuffer.get(bufferHead);
            if (Arrays.equals(head, bufferHead)) {
                //找到头
                request.addData(bufferHead);
                if (getNext() != null) {
                    getNext().handleRequest(request);
                    return;
                }
            } else {
                byteBuffer.reset();
                //position +1继续找
                byteBuffer.get();
            }
        }
        //所有数据都为无效数据，清除掉
        byteBuffer.clear();
    }
    private byte[] getHeader() {
        return new byte[]{(byte) 0xEC};
    }
}